package com.ynwt.service;

import com.github.sd4324530.fastweixin.api.CustomAPI;
import com.github.sd4324530.fastweixin.api.MediaAPI;
import com.github.sd4324530.fastweixin.message.ImageMsg;
import com.github.sd4324530.fastweixin.message.TextMsg;
import com.ynwt.domain.ReplyMsg;
import com.ynwt.domain.User;
import com.ynwt.constant.ReplyMsgKeyword;
import com.ynwt.enums.ReplyMsgType;
import com.ynwt.model.sign.SignResponse;
import com.ynwt.repository.ReplyMsgDao;
import com.ynwt.repository.UserDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by huangying on 2017/4/27.
 */
@Service
public class MsgServiceImpl implements MsgService {

    private final static Logger LOG = LoggerFactory.getLogger(MsgServiceImpl.class);

    private static final String PLACEHOLDER_A = "#a#";

    private static final String PLACEHOLDER_YCOIN = "#ycoin#";

    /**
     * 自动回复
     * @param openid
     * @param keyWord
     */
    @Override
    public void autoReply(String openid, String keyWord) {

        LOG.debug("method: autoReply. msg: auto reply msg (自动回复客服消息。。。). openid: {}. keyWord:{}.",openid, keyWord);

        List<ReplyMsg> list = replyMsgDao.findByKeyWordOrderByPriority(keyWord);
        ReplyMsg replyMsg;

        if (list.size() > 0) {//查找关键字的列表
            for (ReplyMsg msg : list) {
                sendMsg(msg, openid);
            }
        } else {//回复默认内容
            list = replyMsgDao.findByKeyWordOrderByPriority(ReplyMsgKeyword.DEFAULT);
            if (list.size() > 0) {
                replyMsg = list.get(0);
                sendMsg(replyMsg, openid);
            }
        }
    }

    @Override
    public void sendSubscribeAutoReplyMsg(String openid) {
        List<ReplyMsg> list = replyMsgDao.findByKeyWordOrderByPriority(ReplyMsgKeyword.SUBSCRIBE);
        for (ReplyMsg replyMsg : list) {
            sendMsg(replyMsg, openid);
        }
    }

    /**
     * 发送客服消息
     * @param replyMsg
     * @param openid
     */
    private void sendMsg(ReplyMsg replyMsg, String openid) {
        if (replyMsg.getMsgType() == ReplyMsgType.TEXT) {
            String text;
            if (null == replyMsg.getUrl() || "".equals(replyMsg.getUrl())) {
                text = replyMsg.getText();
            } else {
                text = replyMsg.getText();
                text = text.replaceFirst(PLACEHOLDER_A, "<a href=\"" + replyMsg.getUrl() + "\">").replaceFirst(PLACEHOLDER_A, "</a>");
            }
            LOG.debug("method: sendMsg. msg: send msg. result msg: {}.", text);
            customAPI.sendCustomMessage(openid, new TextMsg(text));
        } else if (replyMsg.getMsgType() == ReplyMsgType.IMAGE) {
            customAPI.sendCustomMessage(openid, new ImageMsg(replyMsg.getMediaId()));
        }
    }

    public void sendQueryYcoinReplyMsg(String openid) {
        Long ycoin = searchService.getYcoin(openid);
        if (ycoin > -1) {
            List<ReplyMsg> list = replyMsgDao.findByKeyWordOrderByPriority(ReplyMsgKeyword.MY_YCOIN);
            for (ReplyMsg msg : list) {
                if (msg.getMsgType() == ReplyMsgType.TEXT) {
                    String text;
                    if (null == msg.getUrl() || "".equals(msg.getUrl())) {
                        text = msg.getText();
                    } else {
                        text = msg.getText();
                        text = text.replaceFirst(PLACEHOLDER_A, "<a href=\"" + msg.getUrl() + "\">")
                                .replaceFirst(PLACEHOLDER_A, "</a>").replace(PLACEHOLDER_YCOIN, String.valueOf(ycoin));
                    }
                    LOG.debug("method: sendMsg. msg: send msg. result msg: {}.", text);
                    customAPI.sendCustomMessage(openid, new TextMsg(text));
                } else if (msg.getMsgType() == ReplyMsgType.IMAGE) {
                    customAPI.sendCustomMessage(openid, new ImageMsg(msg.getMediaId()));
                }
            }
        }
    }

    @Override
    public void totalYcoinRank(String openid) {

    }

    @Override
    public void weekYcoinRank(String openid) {

    }

    /**
     * 发送签到结果
     *
     * @param openid
     */
    @Override
    public void sendSignResult(String openid) {

        StringBuffer reMsg = new StringBuffer();

        User user = userDao.findOne(openid);

        SignResponse response = signService.sign(user);
        if (null != response) {
            if (null != response && response.isSuccess()) {
                reMsg.append("亲爱的环球小伙伴，恭喜你今天签到成功，累计签到【")
                        .append(response.getTotalSignTimes())
                        .append("】天。\n\n你由于早起学习，获得了【")
                        .append(response.getYcoin() - response.getSuccessionYcoin())
                        .append("】个逸贝，");
                if (response.getSuccessionYcoin() > 0) {
                    reMsg.append("由于坚持连续早起【")
                            .append(response.getSuccessionTimes())
                            .append("】天，额外获得【")
                            .append(response.getSuccessionYcoin())
                            .append("】个逸贝，今天一共获得【")
                            .append(response.getYcoin())
                            .append("】个逸贝。连续签到天数越多，奖励越丰厚哦～");
                } else {
                    reMsg.append("坚持连续签到，会有惊喜哦～");
                }
                reMsg.append("\n\n坚持每一天就会成功！");
            } else if (response.getCode() == 50101) {
                reMsg.append("亲爱的环球小伙伴，每天只能签到一次，记得坚持早起哦～\n\n温馨提示：坚持连续签到，会有惊喜哦～");
            } else if (response.getCode() == 50102) {
                reMsg.append("亲爱的环球小伙伴，今天已经过了签到时间，每天的签到时间是【01:00-09:00】，明天争取早起签到哦～\n\n温馨提示：坚持连续签到，会有惊喜哦～");
            }

            customAPI.sendCustomMessage(openid, new TextMsg(reMsg.toString()));
        } else {
            customAPI.sendCustomMessage(openid, new TextMsg("系统繁忙，请过几分钟后再重试～"));
        }

    }


    @Value("${backGroundImage}")
    private String backGroundImage;

    @Autowired
    private EventService eventService;

    @Autowired
    private SearchService searchService;

    @Autowired
    private ReplyMsgDao replyMsgDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private CustomAPI customAPI;

    @Autowired
    private MediaAPI mediaAPI;

    @Autowired
    private RankService rankService;

    @Autowired
    private SignService signService;
}
